import asyncio
import json
from typing import List, Literal, Union

from openai import OpenAI
from openai import AsyncOpenAI
from openai.lib.streaming._assistants import AsyncAssistantEventHandler
from openai.types.beta import VectorStore
from openai.types.beta.assistant import Assistant
from openai.types.beta.thread import Thread

from langgraph_sdk import get_sync_client
from langgraph_sdk.schema import Thread as Graph_Thread

from llm.models import Assistants, Threads
from users.models import Users

client = OpenAI()
dev_url = "http://localhost:2024"
graph_client = get_sync_client()


class ThreadService:

    @classmethod
    def create(cls, user_id: str, version: Literal["openai", "langgraph"] = "openai") -> Union[Thread, Graph_Thread]:
        """
        创建一个新的线程，并与用户的user_id绑定,并存储到数据库中
        :param version: 
        :param user_id:
        :return:
        """
        if version == "openai":
            thread = client.beta.threads.create(
                metadata={
                    "thread_name": "智慧家庭-执行窗口",
                    "user_id": user_id
                }
            )
            Threads.objects.create(thread_id=thread.id, user_id_id=user_id)
            return thread
        elif version == "langgraph":
            thread = graph_client.threads.create(
                metadata={
                    "thread_name": "智慧家庭-执行窗口",
                    "user_id": user_id
                }
            )
            Threads.objects.create(thread_id=thread["thread_id"], user_id_id=user_id)
            return thread

    @classmethod
    def get_all(cls, user: Users) -> List[Threads]:
        """
        获取当前用户的所有Thread
        :param user:
        :return:
        """
        # 不管啦！全面使用Langgraph的，这个就不兼容了，数据库表设计的时候没考虑这点，难绷。
        # TODO: 调整优化数据库设计，还是要改的。。。
        return Threads.objects.filter(user_id=user)

    @classmethod
    def get_history_messages(cls, thread_id,version: Literal["openai", "langgraph"] = "openai"):
        """
        获取当前线程的所有历史消息
        :param version:
        :param thread_id:
        :param
        :return:
        """
        if version == "openai":
            print(f"获取当前线程的所有历史消息: {thread_id}")
            # TODO:OpenAI SDK的获取历史消息的条数有上限
            history_messages = client.beta.threads.messages.list(
                thread_id=thread_id,
                limit=100,
                order="desc"
            )
            message_count = 0
            message_list: list = []
            print(f"历史消息: {history_messages.data}")
            for message in history_messages.data:
                print(f"metadata: {message.metadata}")
                print(message)
                metadata: dict | None = message.metadata
                if metadata != {}:
                    if (message.role == "assistant" and metadata['type'] == '1') or (
                            message.role == "user" and metadata['type'] == '2'):
                        message_data: dict = {
                            "message_role": message.role,
                            "message_content": message.content[0].text.value,
                            "created_at": message.created_at
                        }
                        message_list.append(message_data)
                        print(message_data)
                        message_count += 1  # 增加消息计数
                else:
                    continue

            # 打印处理的消息总数
            print(f"消息总数: {message_count}")
            return message_list
        elif version == "langgraph":
            print(f"获取当前线程的所有历史消息: {thread_id}")
            messages=graph_client.threads.get_history(
                thread_id=thread_id
            )[-1]["values"]["messages"]